package chatdialogservicelogic

import (
	"context"
	"time"

	dialogmodel "paper-pro/app/chat/model/chatdialog"
	"paper-pro/app/chat/rpc/internal/svc"
	"paper-pro/app/chat/rpc/pb"
	"paper-pro/pkg/constants"
	delchattask "paper-pro/pkg/types"
	"paper-pro/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

var ErrDialogNoExistsError = xerr.NewErrMsg("聊天会话不存在")

func NewDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteLogic {
	return &DeleteLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteLogic) Delete(in *pb.ChatDialogDeleteReq) (*pb.ChatDialogDeleteResp, error) {
	_, err := l.svcCtx.RedisClient.Publish(constants.ChatDialogDeleteEvent, in.Id)
	if err != nil {
		return nil, errors.Wrapf(err, "Delete Chat Dialog failed: Id: %s, 发布删除消息失败", in.Id)
	}

	deleteDialog, err := l.svcCtx.ChatDialogModel.Delete(l.ctx, in.Id, in.UserId)
	if err != nil && err != dialogmodel.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"删除ID: %s Chat Dialog失败，err: %v", in.Id, err)
	}
	if deleteDialog == nil {
		return nil, errors.Wrapf(ErrDialogNoExistsError, "Delete Chat Dialog ID:%s", in.Id)
	}

	taskPayload, err := delchattask.DelOneDialogPayload(deleteDialog.ID.Hex(), deleteDialog.UserId)
	if err != nil {
		l.Errorf("DeleteChatDialog Id: %s: delay delete chat msgs: Marshal task error: %v", deleteDialog.ID.Hex(), err)
	}
	_, err = l.svcCtx.DqPusherClient.Delay(taskPayload, time.Minute*5)
	if err != nil {
		l.Errorf("DeleteChatDialog Id: %s: delay delete chat msgs:push delay queue error: %v", deleteDialog.ID.Hex(), err)
	}

	var respDialog pb.ChatDialog
	err = copier.Copy(&respDialog, &deleteDialog)
	if err != nil {
		l.Errorf("Delete Chat Dialog ID: %s 数据转换失败，error: %v", deleteDialog.ID.Hex(), err)
	}
	respDialog.Id = deleteDialog.ID.Hex()
	respDialog.AssistantId = deleteDialog.AssistantId.Hex()

	return &pb.ChatDialogDeleteResp{
		Dialog: &respDialog,
	}, nil
}
